package com.jack.blog.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
@ComponentScan({"com.jack.blog.controller"})
@EnableWebMvc
public class MvcConfig {
    /**
     * integrate thymeleaf
     *
     * @return
     */
    @Bean
    public ITemplateResolver iTemplateResolver(){
        SpringResourceTemplateResolver resourceTemplateResolver = new SpringResourceTemplateResolver();
        resourceTemplateResolver.setPrefix("classpath:/pages/");
        resourceTemplateResolver.setSuffix(".html");
        resourceTemplateResolver.setTemplateMode(TemplateMode.HTML);
        resourceTemplateResolver.setCharacterEncoding("UTF-8");
        resourceTemplateResolver.setCacheable(false);
        resourceTemplateResolver.setOrder(0);
        return resourceTemplateResolver;
    }
    @Bean
    public TemplateEngine templateEngine(ITemplateResolver resourceTemplateResolver){
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(resourceTemplateResolver);
        return engine;
    }
    @Bean
    public ThymeleafViewResolver getThymeleafViewResolver(TemplateEngine engine) {
        ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
        thymeleafViewResolver.setTemplateEngine(engine);
        thymeleafViewResolver.setContentType("text/html; charset=utf-8");
        return thymeleafViewResolver;
    }

    /**
     * multipart/form-data
     */
    @Bean("multipartResolver")
    public MultipartResolver getMultipartResolver()throws Exception{
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        commonsMultipartResolver.setDefaultEncoding("UTF-8");
        commonsMultipartResolver.setMaxUploadSize(5242880);
        commonsMultipartResolver.setUploadTempDir(new ClassPathResource(""));
        return commonsMultipartResolver;
    }
}
